1 using System.Collections;
2 using System.Collections.Generic;
3 using UnityEngine;
4
5 public class Ball : MonoBehaviour
6 {
7 private Paddle paddle;
8 private bool hasStarted = false;
9 //needed for unity 5 coding
10 private Rigidbody2D paddleToBallVector;
11 private Vector3 ballStartPosition;
12 // Use this for initialization
13 void Start()
14 {
15 //Account for scripting LvlMng, Paddle, Ball
16 paddle = GameObject.FindObjectOfType<Paddle>();
17
18 //Getting rigid body info
19 paddleToBallVector = GetComponent<Rigidbody2D>();
20 ballStartPosition = this.transform.position - paddle.transform.position;
21 }
22
23 // Update is called once per frame
24 void Update()
25 {
26 if (!hasStarted)
27 {
28 // Lock the ball relative to the paddle
29 this.transform.position = paddle.transform.position + ballStartPosition;
30 }
31 //Wait for left mouse click to launch the ball
32 if (Input.GetMouseButtonDown(0))
33 {
34 print("Mouse clicked, launch ball");
35 hasStarted = true;
36 //Since we are now using rigid body, we can call the velocity for Vector2
37 this.paddleToBallVector.velocity = new Vector2(2f, 10f);
38 }
39 }
40
41 private void OnCollisionEnter2D(Collision2D collision)
42 {
43 Vector2 breakEndlessLoops = new Vector2(Random.Range(0f, 0.2f), Random.Range(0f, 0.2f));
44
45 if (hasStarted)
46 {
47 GetComponent<AudioSource>().Play();
48 this.GetComponent<Rigidbody2D>().velocity += breakEndlessLoops;
49 }
50 }
51 }